package com.kaily.timemanager.net;


import android.text.TextUtils;

import com.kaily.timemanager.BuildConfig;
import com.kaily.timemanager.data.DataCallback;
import com.kaily.timemanager.obj.HttpResult;
import com.kaily.timemanager.obj.TaskClass;

import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 请求类
 */
public class ApiClient {
    private static Retrofit mRetrofit;
    private ApiStores apiStores;

    private ApiClient() {
        retrofit();
        apiStores = mRetrofit.create(ApiStores.class);
    }

    private static Retrofit retrofit() {
        if (mRetrofit == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();

            if (BuildConfig.DEBUG) {
                // Log信息拦截器
                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                //设置 Debug Log 模式
                builder.addInterceptor(loggingInterceptor);
            }
            OkHttpClient okHttpClient = builder.build();
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(ApiStores.API_SERVER_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(okHttpClient)
                    .build();
        }
        return mRetrofit;
    }

    public ApiStores getApiStores() {
        return apiStores;
    }

    public void request(Observable observable, DataCallback<List<TaskClass>> apiCallback) {

        observable.map(new HttpResultFunc<HttpResult>()).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(apiCallback);
    }

    /**
     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T> Subscriber真正需要的数据类型，也就是Data部分的数据类型
     */
    private class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {

        @Override
        public T call(HttpResult<T> httpResult) {

            if (httpResult == null) {
                throw new ApiException("请求失败");
            }
            if (httpResult.getCode() == ApiException.USER_NOT_LOGIN) {
                throw new ApiException(ApiException.USER_NOT_LOGIN);
            }

            if (httpResult.getCode() != ApiException.API_REQUEST_SUCCESS) {
                String msg = httpResult.getMessage();
                if (TextUtils.isEmpty(msg)) {
                    msg = "请求失败";
                }
                throw new ApiException(msg);
            }

            return httpResult.getData();


        }
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final ApiClient INSTANCE = new ApiClient();
    }

    //获取单例
    public static ApiClient getInstance() {
        return SingletonHolder.INSTANCE;
    }

}
